﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace iTelluro.Explorer.Domain.Seedwork
{
   
    public static class EntityEx
    {
        /// <summary>
        /// 将实体集合转换为表结构
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="items">实体集合</param>
        /// <param name="tableName">表名称</param>
        /// <returns>数据表</returns>
        public static DataTable ToDataTable<T>(this IEnumerable<T> items, string tableName) where T : Entity
        {
            if (items == null) return null;
            var table = new DataTable(tableName);
            var t = typeof(T);
            //只取系统类型过滤掉自定义类型
            var props = t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase)
                .Where(s => s.PropertyType.Namespace == "System" && s.DeclaringType.FullName.Contains("iTelluro.Explorer.Domain.MainBoundedContext.Entities")).ToList();
            var columns = props.Select(s => new DataColumn(s.Name)).ToArray();
            table.Columns.AddRange(columns);
            foreach (var item in items)
            {
                var row = table.NewRow();
                foreach (var p in props)
                {
                    var val = p.GetValue(item, null);
                    if (val == null)
                        row[p.Name] = DBNull.Value;
                    else
                        row[p.Name] = val;
                }
                table.Rows.Add(row);
            }
            return table;
        }
        //public static IDataReader ToDataReader<T>(this IEnumerable<T> items, string tableName) where T : Entity
        //{
        //    var reader = items.ToDataTable(tableName).CreateDataReader();
        //    return reader;
        //}
    }
}
